package cn.yunhe.vote.servlet;

import cn.yunhe.vote.entity.Vote;
import cn.yunhe.vote.service.IVoteService;
import cn.yunhe.vote.service.VoteService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class VoteServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String[] arr = request.getParameterValues("itmes");

        if (arr==null) {
            out.print("<script>alert('请选择一个选项');location.href='vote.html'</script>");
            return;
        }

        int id = Integer.parseInt(arr[0]);

        IVoteService voteService = new VoteService();
        boolean flag = voteService.addVote(id);
        if (flag) {
            List<Vote> list = voteService.allVote();
            request.setAttribute("list", list);
            request.getRequestDispatcher("scu.jsp").forward(request, response);
        } else {
            response.sendRedirect("vote.html");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
